package com.halobop.demo.admin.controller;


import com.halobop.demo.admin.dto.UserLoginDto;
import com.halobop.demo.admin.dto.UserQueryDto;
import com.halobop.demo.admin.dto.UserRegisterDto;
import com.halobop.demo.admin.service.IUserService;
import com.halobop.demo.common.CommonPage;
import com.halobop.demo.common.CommonResult;
import com.halobop.demo.common.IErrorCode;
import com.halobop.demo.common.ResultCode;
import com.halobop.demo.mbg.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/user")
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/register")
    public CommonResult register(@Valid UserRegisterDto registerUserDto, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return CommonResult.validateFailed();
        }
        int result = userService.register(registerUserDto);
        if (result > 0){
            return CommonResult.success(null, "注册成功, 请用该账号登录");
        }else {
            return CommonResult.failed("注册失败");
        }
    }

    @PostMapping("/login")
    public CommonResult register(@Valid UserLoginDto dto, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return CommonResult.validateFailed();
        }
        Long userId = userService.login(dto);
        if (userId == null){
            return CommonResult.failed("登录失败，账号或密码错误");
        }else {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("userId", userId);
            return CommonResult.success(resultMap, "登录成功");
        }
    }

    @GetMapping("/pagelist")
    public CommonResult pageList(@Valid UserQueryDto dto, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            return CommonResult.validateFailed();
        }
        List<User> userList = userService.pagelist(dto);
        return CommonResult.success(CommonPage.restPage(userList));
    }

}
